using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using System;

namespace Super
{
	/// <summary>
	/// widget代理，所有widget打开都需要通过这个代理类实现
	/// </summary>
	public class WidgetProxy
	{
		// public string widgetName;
		public Type widgetType;
		public Transform parent;
		private WidgetBase widget;
		public Tween scaleWidgetTween;

		/// <summary>
		/// 初始化代理
		/// </summary>
		/// <param name="T">Widget的类型</param>
		/// <param name="parent">widget位于的transform下</param>
		public WidgetProxy(Type type, Transform parent)
		{
			this.widgetType = type;
			this.parent = parent;
		}

		/// <summary>
		/// 加载widget
		/// </summary>
		/// <returns></returns>
		private WidgetBase LoadWidget()
		{
			if (widget == null)
			{
				string addr = (string)widgetType.GetField("addr").GetValue(null);
				GameObject prefab = AssetUtil.LoadAsset<GameObject>(addr);
				GameObject GO = GameObject.Instantiate(prefab, Vector3.zero, Quaternion.identity);
				GO.transform.SetParent(parent, false);
				GO.transform.SetAsLastSibling();
				GO.name = widgetType.Name;
				widget = GO.GetComponent<WidgetBase>();
			}
			return widget;
		}

		public void Open(params object[] args)
		{
			widget = LoadWidget();
			widget.gameObject.SetActive(true);
			widget.Open(args);
		}

		public bool IsOpen()
		{
			if (widget == null) return false;

			return widget.gameObject.activeSelf;
		}

		public void SetPos(Vector3 pos)
		{
			widget.transform.position = pos;
		}
		
		public void SetLocalPos(Vector3 pos)
		{
			widget.transform.localPosition = pos;
		}

		public void SetPivot(Vector2 pivot)
		{
			widget.GetComponent<RectTransform>().pivot = pivot;
		}
		
		public void Close()
		{
			widget?.Close();
		}

		public Tween DoScale(float scaleStart, float scaleEnd, float scaleTime)
		{
			scaleWidgetTween.Kill();
			widget.transform.localScale = Vector3.one * scaleStart;
			scaleWidgetTween = widget.transform.DOScale(scaleEnd, scaleTime);
			scaleWidgetTween.OnKill(()=> widget.transform.localScale = Vector3.one * scaleEnd);
			return scaleWidgetTween;
		} 
	}

}
